<?php
class ABController{
	protected $o_tpl;
	protected $a_models = array();
	protected $a_vars = array();
	protected $a_conf = array();
	protected $a_session = array();
	protected $b_persistent = false;
	protected $s_sessionname = __CLASS__;

	function __construct(ABView $o_tpl){
		$this->a_conf = ABConf::getAll();
		$this->o_tpl = $o_tpl;
		$this->loadModel();
		if($this->b_persistent){
			session_name($this->s_sessionname);
			session_start();
			$this->a_session = $_SESSION;
		}
	}

	/*
	 * Method used for common all action
	 */
	protected function finalize(){}
	/*
	 * Make redirect to other controller o action, use HTTP redirect
	 */
	protected function redirect($s_control, $s_action =''){
		$s_url = $s_control .'/'. $s_action;
		ABApi::redirect($s_url, true);
	}

	protected function render($only_view = false, $s_view = '', $s_tpl = ''){
		if (!empty($s_view)){
			$this->o_tpl->changeRender($s_view, $s_tpl);
		}
		$this->finalize();
		$this->o_tpl->multi = $this->a_vars;
		$this->o_tpl->render($only_view);
		die();
	}

	protected function notFound(){
		$this->setView('notfound');
		$this->ptitle = 'Pagina no encontrada';
		$this->request = __CLASS__;
		header('HTTP/1.0 404 Not Found');
	}

	protected function setResponse($s_type){
		header("Content-type:  $s_type");
	}

	protected function loadModel(){
		$a_models =func_num_args() == 0 ? $this->a_models: func_get_args() ;
		$s_path = PATH_CORE.'/model/';
		foreach($a_models as $s_model){
			$s_file = $s_path . $s_model .'.class.php';
			if(is_file($s_file)){
				include_once $s_file;
			}else{
				trigger_error("Models $s_model not found!");
			}
		}
	}

	protected function session($s_key, $m_value = null){
		if($m_value === null){
			return isset($this->a_session[$s_key])?unserialize($this->a_session[$s_key]): false;
		}else{
			$this->a_session[$s_key] = serialize($m_value);
			return true;
		}
	}

	protected function post($s_key){
		return isset($_POST[$s_key])?$_POST[$s_key]: false;
	}

	function __destruct(){
		foreach($this->a_session as $s_key => $s_value){
			$_SESSION[$s_key] = $s_value;
		}
	}

	public function __set($s_name, $m_value){
		if($s_name == 'multi' && is_array($m_value)){
			foreach($m_value as $s_key=>$s_value){
				$this->a_vars[$s_key] = $s_value;
			}
		}else{
			$this->a_vars[$s_name] = $m_value;
		}
	}
}
